from rest_framework import serializers
from .models import CanvasElement, TextElement, MaskElement
from ..AssetsManagement.serializers import AssetSerializer
from ..FontManagement.models import Font
from ..FontManagement.serializers import FontSerializer


class TextElementSerializer(serializers.ModelSerializer):
    font_detail = FontSerializer(source='font', read_only=True)  # 用于显示字体详情
    font = serializers.PrimaryKeyRelatedField(  # 用于更新字体ID
        queryset=Font.objects.all(),
        required=False,
        write_only=True
    )

    class Meta:
        model = TextElement
        fields = '__all__'
        extra_kwargs = {
            'element': {'read_only': True}
        }

    def to_representation(self, instance):
        """自定义序列化输出"""
        ret = super().to_representation(instance)
        # 移除write_only的font字段
        ret.pop('font', None)
        return ret

    def update(self, instance, validated_data):
        """处理更新操作"""
        # 从validated_data中获取新的font值(如果有)
        new_font = validated_data.pop('font', None)
        if new_font is not None:
            instance.font = new_font

        # 更新其他字段
        for attr, value in validated_data.items():
            setattr(instance, attr, value)

        instance.save()
        return instance


class MaskElementSerializer(serializers.ModelSerializer):
    class Meta:
        model = MaskElement
        fields = '__all__'
        extra_kwargs = {'element': {'read_only': True}}

    def to_representation(self, instance):
        # 获取默认的序列化数据
        data = super().to_representation(instance)

        # 当蒙版类型为图片时，替换asset字段为资源详情
        if instance.mask_type == 'image':
            if instance.asset:
                data['asset'] = AssetSerializer(instance.asset).data
            else:
                data['asset'] = None
        else:
            # 非图片类型时，移除asset字段
            data.pop('asset', None)

        return data


class CanvasElementSerializer(serializers.ModelSerializer):
    text_element = TextElementSerializer(read_only=True)
    mask_element = MaskElementSerializer(read_only=True)
    canvas = serializers.CharField(source='canvas.id', read_only=True)
    canvas_name = serializers.CharField(source='canvas.name', read_only=True)

    class Meta:
        model = CanvasElement
        fields = '__all__'


class CreateCanvasElementSerializer(serializers.ModelSerializer):
    text_element = TextElementSerializer(required=False)
    mask_element = MaskElementSerializer(required=False)

    class Meta:
        model = CanvasElement
        fields = ['canvas', 'type', 'name', 'position', 'size', 'rotation', 'frame_style',
                  'opacity', 'visible', 'locked', 'text_element', 'mask_element']

    def validate(self, data):
        if data.get('type') == 'text' and not data.get('text_element'):
            raise serializers.ValidationError("text_element 字段对于文本类型是必需的")
        if data.get('type') == 'mask' and not data.get('mask_element'):
            raise serializers.ValidationError("mask_element 字段对于蒙版类型是必需的")
        return data

    def create(self, validated_data):
        text_data = validated_data.pop('text_element', None)
        mask_data = validated_data.pop('mask_element', None)
        element = CanvasElement.objects.create(**validated_data)

        if element.type == 'text' and text_data:
            TextElement.objects.create(element=element, **text_data)
        elif element.type == 'mask' and mask_data:
            MaskElement.objects.create(element=element, **mask_data)
        return element


class UpdateCanvasElementSerializer(serializers.ModelSerializer):
    id = serializers.CharField(required=True)
    text_element = TextElementSerializer(required=False)
    mask_element = MaskElementSerializer(required=False)

    class Meta:
        model = CanvasElement
        fields = ['id', 'name', 'position', 'size', 'rotation', 'opacity', 'frame_style',
                  'visible', 'locked', 'z_index', 'text_element', 'mask_element']
        extra_kwargs = {
            field: {'required': False}
            for field in fields if field != 'id'
        }

    def update(self, instance, validated_data):
        text_data = validated_data.pop('text_element', None)
        mask_data = validated_data.pop('mask_element', None)

        # 更新 CanvasElement 基础字段
        super().update(instance, validated_data)

        # 处理子模型更新
        if instance.type == 'text' and text_data:
            TextElement.objects.filter(element=instance).update(**text_data)
        elif instance.type == 'mask' and mask_data:
            MaskElement.objects.filter(element=instance).update(**mask_data)
        return instance


class BatchUpdateElementSerializer(serializers.Serializer):
    """批量更新元素序列化器"""
    elements = UpdateCanvasElementSerializer(many=True)

    def validate_elements(self, value):
        if not value:
            raise serializers.ValidationError("elements不能为空")
        return value


class BatchUpdateResultSerializer(serializers.Serializer):
    """批量更新结果序列化器"""
    updated_elements = CanvasElementSerializer(many=True)
    failed = serializers.DictField(
        child=serializers.CharField(),
        allow_empty=True
    )
